package com.redwood.report.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.redwood.report.ItemDecoration.SpaceItemDecoration;
import com.redwood.report.R;
import com.redwood.report.adapter.HistoryItemAdapter;
import com.redwood.report.base.BaseActivity;
import com.redwood.report.entity.BarDataBeen;
import com.redwood.report.entity.HistoryBarChartBeen;
import com.redwood.report.entity.HistoryPieChartBeen;
import com.redwood.report.entity.HistoryTipstBeen;
import com.redwood.report.entity.JitaiBeen;
import com.redwood.report.entity.JtreCordAllInfo;
import com.redwood.report.entity.ServiceResult;
import com.redwood.report.net.Api;
import com.redwood.report.net.NetUtils;
import com.redwood.report.util.ToastUtils;
import com.redwood.report.util.Utils;
import com.redwood.report.widget.dialog.PickTimePopWin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sp on 2018/12/12.
 * 历史查询
 */

public class LishiChaXunActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_data)
    ImageView ivData;
    @BindView(R.id.title_bar)
    RelativeLayout titleBar;
    @BindView(R.id.tv_timernow)
    TextView tvTimernow;
    @BindView(R.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    private PickTimePopWin mPickTimePopWin;
    public static String dateTimerStr;
    private SimpleDateFormat formatter;
    private long timer;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    private BaseQuickAdapter homeAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lishichaxun);
        ButterKnife.bind(this);
        initView();
        initAdapter();
    }

    private void initAdapter() {
        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.addItemDecoration(new SpaceItemDecoration(getActivity()).setSpace(0f).setSpaceColor(getResources().getColor(R.color.blueColorAppKey)));
        homeAdapter = new HistoryItemAdapter(null);
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
        homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
        rvList.setAdapter(homeAdapter);

        loadByServer(dateTimerStr);
    }

    private void loadByServer(String dateTimerStr) {
        Api.jtrecordAll(getActivity(), dateTimerStr, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                refreshLayout.setRefreshing(false);
                if (rspData.getRecode() == 1) {
                    int zaixianmaoshu = 0;
                    int lixianmaoshu = 0;
                    int guzhangmaoshu = 0;
                    int daijimaoshu = 0;
                    JtreCordAllInfo jtreCordAllInfo = (JtreCordAllInfo) rspData;
                    List<JtreCordAllInfo.InfoBean> infoBeanList = jtreCordAllInfo.getInfo();
                    List<JtreCordAllInfo.JitaiBeec> jitaiBeenList=jtreCordAllInfo.getJitai();
                    if (infoBeanList == null || infoBeanList.size() == 0) {
                        return;
                    }
                    LinkedHashMap<String, List<BarDataBeen>> linkedHashMap = new LinkedHashMap<>();
                    HashMap<String,String> hashMapName=new HashMap<>();
                    int tbcolor = mContext.getResources().getColor(R.color.main_gray);
                    for(JtreCordAllInfo.JitaiBeec jitaiBeec:jitaiBeenList){
                            hashMapName.put(jitaiBeec.getXtbianhao(),jitaiBeec.getBianhao());
                        linkedHashMap.put(jitaiBeec.getXtbianhao(), new ArrayList<BarDataBeen>());
                    }
                    for (JtreCordAllInfo.InfoBean infoBean : infoBeanList) {
                            List<BarDataBeen> barDataBeenLists = linkedHashMap.get(infoBean.getXtbihao());
                        if ("RUN".equals(infoBean.getZtype())) {
                            zaixianmaoshu = zaixianmaoshu + infoBean.getMiaoshu();
                            tbcolor = mContext.getResources().getColor(R.color.main_green);
                        } else if ("FREE".equals(infoBean.getZtype()) || "MOULD".equals(infoBean.getZtype())) {
                            daijimaoshu = daijimaoshu + infoBean.getMiaoshu();
                            tbcolor = mContext.getResources().getColor(R.color.main_yellow);
                        } else if ("BAD".equals(infoBean.getZtype())) {
                            guzhangmaoshu = guzhangmaoshu + infoBean.getMiaoshu();
                            tbcolor = mContext.getResources().getColor(R.color.main_red);
                        }
                        BarDataBeen barDataBeen = new BarDataBeen();
                        barDataBeen.setColor(tbcolor);
                        float timer=Utils.intFloatTuBiao(infoBean.getMiaoshu());
                        if(timer<0.05f){
                            timer=0.05f;
                        }
                        barDataBeen.setTimer(timer);
                        barDataBeenLists.add(barDataBeen);
                    }

                    HistoryPieChartBeen pieChartBeen = new HistoryPieChartBeen();
                    HistoryBarChartBeen historyBarChartBeen = new HistoryBarChartBeen();
                    historyBarChartBeen.setLinkedHashMap(linkedHashMap);
                    historyBarChartBeen.setHashMapName(hashMapName);
                    int allCount = zaixianmaoshu + lixianmaoshu + guzhangmaoshu + daijimaoshu;
                    pieChartBeen.setDaiji((float) daijimaoshu / allCount);
                    pieChartBeen.setLixian((float) lixianmaoshu / allCount);
                    pieChartBeen.setJingdao((float) guzhangmaoshu / allCount);
                    pieChartBeen.setZaixian((float) zaixianmaoshu / allCount);
                    HistoryTipstBeen historyTipstBeen = new HistoryTipstBeen();
                    historyTipstBeen.setZaixianh(Utils.getStingToHour3(zaixianmaoshu));
                    historyTipstBeen.setDaijih(Utils.getStingToHour3(daijimaoshu));
                    historyTipstBeen.setLixianh(Utils.getStingToHour3(lixianmaoshu));
                    historyTipstBeen.setGuzhangh(Utils.getStingToHour3(guzhangmaoshu));
                    List list = new ArrayList();
                    list.add(historyBarChartBeen);
                    list.add(pieChartBeen);
                    list.add(historyTipstBeen);
                    homeAdapter.setNewData(list);
                }
            }

            @Override
            public void failed(String msg) {
                refreshLayout.setRefreshing(false);
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, JtreCordAllInfo.class);

    }

    private void initView() {
        formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        timer = calendar.getTimeInMillis();
        dateTimerStr = formatter.format(timer);
        tvTimernow.setText(dateTimerStr);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
    }

    private void showPickTimeWin() {
        if (mPickTimePopWin == null)
            mPickTimePopWin = new PickTimePopWin(getActivity(), 1);
        mPickTimePopWin.showAtLocation(getActivity().findViewById(R.id.root_layout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        mPickTimePopWin.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
        mPickTimePopWin.setOnSelectListener(new PickTimePopWin.OnSelectListener() {
            @Override
            public void onDateSelect(int year, int mon, int day, int hour, int min) {

                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, mon - 1);
                calendar.set(Calendar.DAY_OF_MONTH, day);
                //   calendar.set(Calendar.HOUR_OF_DAY, hour);
                //   calendar.set(Calendar.MINUTE, min);

                if (System.currentTimeMillis() < calendar.getTimeInMillis()) {
                    ToastUtils.show(R.string.timererror);
                } else {
                    timer = calendar.getTimeInMillis();
                    dateTimerStr = formatter.format(timer);
                }
                tvTimernow.setText(dateTimerStr);
                loadByServer(dateTimerStr);
            }
        });
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.6f;
        getActivity().getWindow().setAttributes(lp);
    }

    @OnClick({R.id.iv_left, R.id.iv_right, R.id.iv_data})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_left:
                timer = timer - 3600 * 24 * 1000;
                dateTimerStr = formatter.format(timer);
                tvTimernow.setText(dateTimerStr);
                loadByServer(dateTimerStr);
                break;
            case R.id.iv_right:
                timer = timer + 3600 * 24 * 1000;
                dateTimerStr = formatter.format(timer);
                tvTimernow.setText(dateTimerStr);
                loadByServer(dateTimerStr);
                break;
            case R.id.iv_data:
                showPickTimeWin();
                break;
        }
    }

    @Override
    public void onRefresh() {
        loadByServer(dateTimerStr);
    }
}
